<template>
<view>
<!--pages/homePage/homePage.wxml-->
<swiper class="homeHeader" indicator-dots autoplay interval="3000" circular skip-hidden-item-layout>
     <swiper-item v-for="(item, index) in homeAdvertises" :key="index" class="swiper">
          <image :src="item.imgSrc" mode="scaleToFill" class="swiper" @tap="homeAdvertisesTap" :data-index="index" :data-name="item.name"></image>
     </swiper-item>
</swiper>

<view class="filterContent">
     <view class="filterView">
          <view class="location">
               <image src="/static/res/images/ic_city_location.png" mode="aspectFit" class="icon" @tap="getLocalLocation"></image>
               <text class="caption" @tap="getLocalLocation">当前城市：</text>
               <text class="city" @tap="selectCity">{{location}}</text>
               <image src="/static/res/images/ic_right_arrow.png" mode="widthFix" class="icon" @tap="selectCity"></image>
          </view>
          <view class="location">
               <view class="filter">
								 <uni-easyinput v-model="number" :inputBorder="false" class="uni-input" focus placeholder="居住人数" type="number" style="text-align: center;"></uni-easyinput>
               </view>
               <view style="color:#ccc;text-align: center;">|
               </view>
               <view class="filter">
								 <uni-easyinput v-model="district" :inputBorder="false" class="uni-input" focus placeholder="附近商圈" style="text-align: center;"></uni-easyinput>
               </view>
          </view>

          <view class="divideItem">
               <text class="divideText">入住</text>
               <text class="divideText">退房</text>
          </view>

          <!-- 日期计算  -->
          <view class="dateContent">
               <view class="dateItem">
                    <picker class="date" mode="date" :value="startDate" :start="currentDate" :end="endOfStartDate" @change="startDateChange">
                         <view class="date">
                              <text class="day">{{startDay}}</text>
                              <view class="monthWeek">
                                   <text class="month">{{startMonth}}月</text>
                                   <text class="week">{{startWeek}}</text>
                              </view>
                         </view>
                    </picker>
                    <view class="horizontalLine" style="width:60rpx;position:absolute;right:0;"></view>
               </view>
               <text class="dayCount">{{dayCount}}天</text>
               <view class="dateItem">
                    <view class="horizontalLine" style="width:60rpx;position:absolute;"></view>
                    <picker class="date" mode="date" :value="endDate" :start="startDate" :end="endOfEndDate" @change="endDateChange">
                         <view class="date">
                              <text class="day">{{endDay}}</text>
                              <view class="monthWeek">
                                   <text class="month">{{endMonth}}月</text>
                                   <text class="week">{{endWeek}}</text>
                              </view>
                         </view>
                    </picker>
               </view>
          </view>
          <!-- 日期end  -->

          <view class="commonBtn" hover-class="commonBtnHover" @tap="searchEvent" hover-stay-time="100">立即搜索</view>
     </view>
</view>
</view>
</template>

<script>
// pages/homePage/homePage.js
var app = getApp();
var locationUrl = 'http://apis.map.qq.com/ws/geocoder/v1/';
const tencentMapKey = 'ZNDBZ-W3YR6-6KXSB-MLKXV-6HFXK-UMFOT';
var currentYear = new Date().getFullYear();
var currentMonth = new Date().getMonth() + 1;
var currentDay = new Date().getDate();
var currentWeek = new Date().getDay();
var currentDate = currentYear + '-' + currentMonth + '-' + currentDay;
var startDate = '';
var startYear;
var startDay;
var startMonth;
var startWeek;
var endOfStartDate = '2021-12-31';
var startDayCount;
var endDate = '';
var endYear;
var endDay;
var endMonth;
var endWeek;
var endOfEndDate = '2021-12-31';
var dayCount = 1;

export default {
  data() {
    return {
      homeAdvertises: [],
      location: '定位中...',
      startDate: '',
      currentDate: '',
      endOfStartDate: '',
      endDate: '',
      endOfEndDate: '',
      startDay: '',
      startMonth: '',
      startWeek: '',
      endDay: '',
      endMonth: '',
      endWeek: '',
			number:'',
			district:'',
      dayCount: 1
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
		this.homePage()
    this.getLocalLocation();
    startDate = currentDate;
    startYear = currentYear;
    startDay = currentDay;
    startMonth = currentMonth;
    startWeek = currentWeek;
    this.initEndDate();
    this.setSearchDate();
  },
	

  methods: {
		// 获取 banner
		homePage(){
			uniCloud.callFunction({
				name: 'homePage',
				success: (res) => {
					res.result.data.map((item)=>{
						this.homeAdvertises.push({
							imgSrc:item.imageUrl,
							name:item.name
						})
					})
					console.log(res)
				}
			})
		},
		
    homeAdvertisesTap: function (e) {
      var index = e.currentTarget.dataset.name;
      uni.showToast({
        title: index,
        icon: 'none'
      });
    },
    getLocalLocation: function () {
      this.setData({
        location: '定位中...'
      });
      var that = this;
      uni.getLocation({
        success: function (res) {
          app.globalData.func.httpRequest(locationUrl, {
            key: tencentMapKey,
            location: res.latitude + ',' + res.longitude
          }, 'GET', {
            'content-type': 'application/json'
          }, function (result) {
            if (result) {
              that.setData({
                location: result.result.address_component.city
              });
            } else {
              that.setData({
                location: '定位失败'
              });
            }
          });
        },
        fail: function (res) {
          that.setData({
            location: '定位失败'
          });
        }
      });
    },
		
    selectCity: function () {
      uni.navigateTo({
        url: '../select_city/select_city'
      });
    },
		
    searchEvent: function () {
      if (location == '定位中...') {
        uni.showToast({
          title: '定位中，请稍后',
          icon: 'none'
        });
      } else {
        uni.navigateTo({
          url: `../../pages/searchHotel/searchHotel?location=${this.location}&number=${this.number}&district=${this.district}`
        });
      }
    },
    startDateChange: function (e) {
      startDate = e.detail.value;
      var startArray = startDate.split('-');
      startYear = parseInt(startArray[0]);
      startDay = parseInt(startArray[2]);
      startMonth = parseInt(startArray[1]);
      startWeek = new Date(startYear, startMonth, startDay).getDay();
      var startFormat = this.formatDate(startDate);
      var endFormat = this.formatDate(endDate);

      if (new Date(endFormat) < new Date(startFormat)) {
        this.initEndDate();
      }

      this.setSearchDate();
    },
    endDateChange: function (e) {
      console.log(e);
      endDate = e.detail.value;
      var endArray = endDate.split('-');
      endYear = parseInt(endArray[0]);
      endDay = parseInt(endArray[2]);
      endMonth = parseInt(endArray[1]);
      endWeek = new Date(endYear, endMonth, endDay).getDay();
      this.setSearchDate();
    },
    getWeekday: function (week) {
      var weekday = new Array(7);
      weekday[0] = "周日";
      weekday[1] = "周一";
      weekday[2] = "周二";
      weekday[3] = "周三";
      weekday[4] = "周四";
      weekday[5] = "周五";
      weekday[6] = "周六";
      return weekday[week];
    },
    prefixInteger: function (num, length) {
      return (Array(length).join('0') + num).slice(-length);
    },
    getDayCount: function (startDate, endDate) {
      var startFormat = this.formatDate(startDate);
      var endFormat = this.formatDate(endDate);
      console.log(startFormat + "->" + endFormat);
      var start = new Date(startFormat);
      var end = new Date(endFormat);
      console.log(start + "->" + end);
      var result = end - start;

      if (result >= 0) {
        var days = parseInt(result / (1000 * 60 * 60 * 24));
        return days == 0 ? 1 : days;
      } else {
        return 0;
      }
    },
    formatDate: function (date) {
      return date.replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '').replace(/(-)/g, '/');
    },
    initEndDate: function () {
      startDayCount = new Date(startYear, startMonth, 0).getDate();

      if (startMonth == 12 && startDay == 31) {
        endYear = startYear + 1;
        endMonth = 1;
        endDay = 1;
      } else {
        endYear = startYear;

        if (startDay <= startDayCount) {
          endMonth = startMonth;
          endDay = startDay + 1;
        } else {
          endMonth = startMonth + 1;
          endDay = 1;
        }
      }

      if (currentWeek >= 7) {
        endWeek = 1;
      } else {
        endWeek = currentWeek + 1;
      }

      endDate = endYear + '-' + endMonth + '-' + endDay;
    },
    setSearchDate: function () {
			app.globalData.startDate = startDate
			app.globalData.endDate = endDate
      this.setData({
        currentDate: currentDate,
        startDate: startDate,
        startDay: this.prefixInteger(startDay, 2),
        startMonth: this.prefixInteger(startMonth, 2),
        startWeek: this.getWeekday(startWeek),
        endOfStartDate: '2021-12-31',
        endDate: endDate,
        endDay: this.prefixInteger(endDay, 2),
        endMonth: this.prefixInteger(endMonth, 2),
        endWeek: this.getWeekday(endWeek),
        endOfEndDate: '2021-12-31',
        dayCount: this.getDayCount(startDate, endDate)
      });
    }
  }
};
</script>
<style>
/* pages/homePage/homePage.wxss */

Page {
     width: 100%;
     height: 100%;
}

.homeHeader {
     width: 100%;
     height: 340rpx;
}

.homeHeader .swiper {
     width: 100%;
     height: 100%;
}

.homeHeader .wx-swiper-dots.wx-swiper-dots-horizontal {
     margin-bottom: 85rpx;
}

.homeHeader .wx-swiper-dot {
     width: 40rpx;
     display: inline-flex;
     height: 10rpx;
     /* margin-left: 20rpx; */
     justify-content: space-between;
}

.homeHeader .wx-swiper-dot::before {
     content: '';
     flex-grow: 1;
     background: white;
     border-radius: 8rpx;
}

.homeHeader .wx-swiper-dot-active::before {
     background: #f66e26;
}

.filterContent {
     width: 100%;
     box-sizing: border-box;
     position: absolute;
     top: 260rpx;
     padding: 0 28rpx;
}

.filterView {
     display: flex;
     flex-direction: column;
     box-sizing: border-box;
     height: max-content;
     width: 100%;
     box-shadow: 0rpx 8rpx 20rpx #bbb;
     border-radius: 14rpx;
     background: white;
}

.location {
     width: 100%;
     height: max-content;
     box-sizing: border-box;
     padding: 22rpx 30rpx;
     display: flex;
     flex-direction: row;
     align-items: center;
     border-bottom: 1rpx solid #eee;
}

.location .icon {
     width: 24rpx;
     height: 24rpx;
}

.location .caption, .location .city, .location .filter .text {
     font-size: 32rpx;
     margin-left: 14rpx;
}

.location .city {
     flex: 1;
}

.location .filter {
     display: flex;
     flex-direction: row;
     flex: 1;
     justify-content: center;
     align-items: center;
}

.location .filter .icon {
     width: 34rpx;
}

.divideItem {
     box-sizing: border-box;
     width: 100%;
     background: white;
     padding: 24rpx;
     display: flex;
     flex-direction: row;
     align-items: center;
}

.divideText {
     flex: 1;
     text-align: center;
     font-size: 24rpx;
     color: #999;
}

.dateContent {
     width: 100%;
     height: max-content;
     display: flex;
     flex-direction: row;
     padding: 10rpx 10rpx 26rpx;
     box-sizing: border-box;
     align-items: center;
     border-bottom: 1rpx solid #eee;
}

.dateItem {
     flex: 1;
     display: flex;
     flex-direction: row;
     align-items: center;
     position: relative;
}

.dateItem .date {
     display: flex;
     flex-direction: row;
     margin: 0 auto;
}

.dateItem .date .day {
     height: fit-content;
     font-size: 45rpx;
     color: #ee6715;
     text-align: center;
}

.dateItem .date .monthWeek {
     height: fit-content;
     display: flex;
     flex-direction: column;
     margin-left: 6rpx;
}

.dateItem .date .monthWeek .week, .dateItem .date .monthWeek .month {
     flex: 1;
     font-size: 22rpx;
}

.dayCount {
     font-size: 32rpx;
     margin: 0 10rpx;
}

</style>